package com.afd.ozblip.chat;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.json.JSONObject;

import com.afd.ozblip.util.Constants;

import android.os.Handler;
import android.os.Message;

public class ClientHandler extends IoHandlerAdapter {

	private static ClientHandler samplMinaClientHandler = null;
	private String userId;
	private Handler uih;

	public static ClientHandler getInstances(String userId) {
		if (null == samplMinaClientHandler) {
			samplMinaClientHandler = new ClientHandler(userId);

		}
		return samplMinaClientHandler;
	}

	private ClientHandler(String userId) {
		this.userId = userId;
	}

	public void setUIHandler(Handler uih) {
		this.uih = uih;
	}

	public void sessionOpened(IoSession session) throws Exception {
		MinaEntity<?> openMina = new MinaEntity<String>(MinaEntityType.LOGIN);
		openMina.setFromUser(this.userId);

		session.write(openMina);
	}

	public void sessionClosed(IoSession session) {
	}

	public void messageReceived(IoSession session, Object message)
			throws Exception {
		System.out.println("收到消息了......");
		System.out.println(message);
		System.out.println(message.getClass().getName());
		String resutlJsonStr = (String) message;
		JSONObject resutlJson = new JSONObject(resutlJsonStr);
		int type = resutlJson.getInt("type");
		switch (type) {
		case 1:
			Message uiMsg = new Message();
			uiMsg.what = Constants.UpdateLV;
			uiMsg.obj = resutlJson.getString("content");
			uih.sendMessage(uiMsg);
			break;
		default:
			break;
		}
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		System.out.println("===============" + cause.getMessage());
	}

	public void messageSent(IoSession arg0, Object arg1) throws Exception {
		System.out.println("客户端已经向服务器发送了：" + arg1);
	}
}